package com.yunxin.core.utils.infra.utils;


import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.common.utils.OkHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zero°
 * @since 2024-01-08
 */
@Slf4j
public enum DingDingMessageUtils {

    /**
     * 实例
     */
    X;

    /**
     * 钉钉通知换行
     */
    public static final String DD_MESSAGE_BR = "\r\n\r\n>";

    public void sendMessage(String title, String content, String messageType, String sendUrl) {
        if (StringUtils.isBlank(sendUrl)) {
            log.warn("钉钉预警地址为空, title:{}", title);
            return;
        }
        try {
            DingRobotMessageTemplateDTO dingRobotMessageTemplateDTO = getDingRobotMessageTemplateDTO(title, content, messageType);
            String contentText = JacksonUtils.X.format(dingRobotMessageTemplateDTO);
            Map<String, String> headers = new HashMap<>();
            headers.put(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
            OkHttpUtils.X.post(sendUrl, contentText, headers);
        } catch (Exception e) {
            log.error("发送钉钉预警失败", e);
        }

    }


    /**
     * getDingRobotMessageTemplateDTO
     * @param title title
     * @param content content
     * @param messageType messageType
     * @return DingRobotMessageTemplateDTO
     */
    private DingRobotMessageTemplateDTO getDingRobotMessageTemplateDTO(String title, String content, String messageType) {
        DingRobotMessageTemplateDTO dingRobotMessageTemplateDTO = new DingRobotMessageTemplateDTO();
        DingRobotMessageTemplateDTO.DingRobotMessageMarkDown dingRobotMessageMarkDown = new DingRobotMessageTemplateDTO.DingRobotMessageMarkDown();
        dingRobotMessageMarkDown.setTitle(title);
        dingRobotMessageMarkDown.setText(content);
        DingRobotMessageTemplateDTO.DingRobotMessageAt dingRobotMessageAt = new DingRobotMessageTemplateDTO.DingRobotMessageAt();
        dingRobotMessageAt.setIsAtAll(true);
        dingRobotMessageTemplateDTO.setMsgtype(messageType);
        dingRobotMessageTemplateDTO.setMarkdown(dingRobotMessageMarkDown);
        dingRobotMessageTemplateDTO.setAt(dingRobotMessageAt);
        return dingRobotMessageTemplateDTO;
    }
}
